<template>

  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" size="large" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>

        <!-- <el-button type="primary" icon="Search" @click="handleSync">同步数据</el-button> -->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="项目统计" name="first">
        <el-row element-loading-text="数据统计中..." :gutter="24">
          <el-col :span="8" :class="userStore.isMobile ? 'mobile-span-24' : ''">
            <div class="statistic-card">
              <el-statistic :value="totalMoney" :formatter="(value) => value.toFixed(2)">
                <template #title>
                  <div style="display: inline-flex; align-items: center;font-size: 16px;">
                    总金额￥
                  </div>
                </template>
              </el-statistic>
            </div>
          </el-col>
          <el-col :span="8" :class="userStore.isMobile ? 'mobile-span-24' : ''">
            <div class="statistic-card">
              <el-statistic :value="already" :formatter="(value) => value.toFixed(2)">
                <template #title>
                  <div style="display: inline-flex; align-items: center;font-size: 16px;">
                    已发放￥
                  </div>
                </template>
              </el-statistic>
            </div>
          </el-col>
          <el-col :span="8" :class="userStore.isMobile ? 'mobile-span-24' : ''">
            <div class="statistic-card">
              <el-statistic :value="wait" :formatter="(value) => value.toFixed(2)">
                <template #title>
                  <div style="display: inline-flex; align-items: center;font-size: 16px;">
                    待发放￥
                  </div>
                </template>
              </el-statistic>
            </div>
          </el-col>
        </el-row>



        <el-table v-loading="loading" :data="projectList" border>
          <el-table-column label="项目名称" show-overflow-tooltip width="220" align="center" prop="projectName" />
          <el-table-column label="合同金额" align="center" show-overflow-tooltip width="150" prop="contractAmount" />
          <el-table-column label="结算金额" align="center" show-overflow-tooltip width="150" prop="settlementAmount" />
          <el-table-column label="客户名称" align="center" show-overflow-tooltip width="220" prop="customerName" />
          <el-table-column label="管家婆项目" align="center" prop="housekeeperName" show-overflow-tooltip width="300" />
          <el-table-column label="总金额" align="center" show-overflow-tooltip width="120" prop="personTotal" />
          <el-table-column label="已发放" align="center" show-overflow-tooltip width="150" prop="already" />
          <el-table-column label="未发放" align="center" show-overflow-tooltip width="150" prop="wait" />
          <!-- 固定操作列 -->
          <el-table-column label="操作" fixed="right" width="220" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
              <el-button link type="primary" icon="Edit" @click="openAllocationDialog(scope.row)">绩效发放确认</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改绩效基本信息对话框 -->
        <el-dialog fullscreen v-model="open" width="800px" append-to-body>
          <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="项目信息" name="first">
              <projectView :key="'projectView' + form.projectNo" :datas="form" :column="3" :sizes="'large'">
              </projectView>
              <!-- 是否有 超级管理员 项目经理 销售 销售负责人 商务 财务权限之一  -->
              <el-divider style="font-size: 16px; font-weight: bold;">项目核算信息1</el-divider>
              <el-button :disabled="!allPer" type="primary" plain :icon="Plus" @click="addProfit()"
                style="margin-bottom: 10px;">添加利润计算</el-button>
              <el-table :summary-method="getSummary" show-summary border v-loading="loading" :data="accountingList"
                @selection-change="handleSelectionChange">
                <el-table-column label="类型" align="center" prop="type">
                  <template #default="scope">
                    <dict-tag :options="profit_type" :value="scope.row.type" />
                  </template>
                </el-table-column>
                <el-table-column label="此类型的结算总额" align="center" width="100" prop="projectAmount" />
                <el-table-column label="项目税额" align="center" width="100" prop="taxAmount" />
                <el-table-column label="项目材料成本" align="center" width="100" prop="materialCost" />
                <el-table-column label="其他成本一(报销费用)" align="center" width="100" prop="costOne" />
                <el-table-column label="其他成本二" align="center" width="100" prop="costTwo" />
                <el-table-column label="其他成本三" align="center" width="100" prop="costThree" />
                <el-table-column label="资金成本" align="center" width="100" prop="fundCost" />
                <el-table-column label="外协人工成本" align="center" width="100" prop="laborCost" />
                <el-table-column label="税率(%)" align="center" prop="rate" />
                <el-table-column label="毛利润" align="center" width="100" prop="profit" />
                <el-table-column label="成本税费" align="center" width="100" prop="costFees" />
                <el-table-column label="差额税费" align="center" width="100" prop="differenceFees" />
                <el-table-column label="税前利润" align="center" width="100" prop="beforeProfit" />
                <el-table-column label="质保金" align="center" width="100" prop="retentionMoney" />
                <el-table-column label="纯利润扣质保金" align="center" width="100" prop="afterProfit" />
                <el-table-column label="项目提成" align="center" width="100" prop="projectCommission" />
                <el-table-column label="操作员" align="center" prop="operator" />
                <el-table-column label="操作" align="center" fixed="right" width="220"
                  class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-button link type="primary" :disabled="!allPer" icon="Edit"
                      @click="handleUpdateProfit(scope.row)">修改</el-button>
                    <el-button link type="primary" :disabled="!allPer" icon="Delete"
                      @click="handleDeleteProfit(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

            </el-tab-pane>
            <el-tab-pane label="正式清单" name="second">
              <mainList v-if="activeName == 'second'" :datas="form"></mainList>
            </el-tab-pane>
            <el-tab-pane label="管家婆出库单" name="third">
              <saleList v-if="activeName == 'third'" :datas="form"></saleList>
            </el-tab-pane>
            <el-tab-pane label="费用汇总" name="four">
              <feeList v-if="activeName == 'four'" :datas="form"></feeList>
            </el-tab-pane>
            <el-tab-pane label="清单对比" name="five">
              <compareMainAndSale v-if="activeName == 'five'" :datas="form"></compareMainAndSale>
            </el-tab-pane>
          </el-tabs>

          <template #footer>
            <div class="dialog-footer">
              <!-- <el-button type="primary" @click="submitForm(1)">保存当前内容</el-button> -->
              <!-- <el-button type="primary" v-if="status == 1"@click="nextPhase()">下一步</el-button> -->
              <el-popconfirm v-if="status == 1 && haveNext" confirm-button-text="确认" cancel-button-text="取消"
                title="确认提交到下一步?" @confirm="nextPhase">
                <template #reference>
                  <el-button type="primary">下一步</el-button>
                </template>
              </el-popconfirm>
              <el-button type="primary" @click="cancel">关 闭</el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 添加或修改付款对话框 -->

        <el-dialog title="利润计算信息" v-model="openProfit" width="700px" append-to-body>
          <el-form ref="accountingRef" size="large" :model="profitForm" :rules="profitRules" label-width="160px">
            <el-form-item label="类型" prop="type">
              <el-select @change="setTypeName" v-model="profitForm.type" placeholder="请选择类型">
                <el-option v-for="dict in profit_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="此类型的结算总额" prop="projectAmount">
              <el-input type="number" @wheel.native.prevent v-model="profitForm.projectAmount"
                placeholder="请输入此类型的结算总额" />
            </el-form-item>
            <el-form-item label="项目材料成本" prop="materialCost">
              <el-input type="number" @wheel.native.prevent :disabled="true" v-model="profitForm.materialCost"
                placeholder="请输入项目材料成本" />
            </el-form-item>
            <el-form-item label="其他成本一(报销费用)" prop="costOne">
              <el-input type="number" @wheel.native.prevent :disabled="true" v-model="profitForm.costOne"
                placeholder="请输入其他成本一" />
            </el-form-item>
            <el-form-item label="其他成本二" prop="costTwo">
              <el-input type="number" @wheel.native.prevent v-model="profitForm.costTwo" placeholder="请输入其他成本二" />
            </el-form-item>
            <el-form-item label="其他成本三" prop="costThree">
              <el-input type="number" @wheel.native.prevent v-model="profitForm.costThree" placeholder="请输入其他成本三" />
            </el-form-item>
            <el-form-item label="资金成本" prop="fundCost">
              <el-input type="number" @wheel.native.prevent v-model="profitForm.fundCost" placeholder="请输入资金成本" />
            </el-form-item>

            <el-form-item label="资金使用时间(月)" prop="costTime">
              <el-input type="number" @wheel.native.prevent v-model="profitForm.costTime" placeholder="资金使用时间" />
            </el-form-item>

            <el-form-item label="人工成本" prop="laborCost">
              <el-input type="number" @wheel.native.prevent v-model="profitForm.laborCost" placeholder="请输入人工成本" />
            </el-form-item>
            <el-form-item label="税率(%)" prop="laborCost">
              <el-input type="number" @wheel.native.prevent v-model="profitForm.rate" :disabled="true" />
            </el-form-item>
            <el-form-item label="质保金" prop="retentionMoney">
              <el-input type="number" @wheel.native.prevent v-model="profitForm.retentionMoney" placeholder="请输入质保金" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="profitForm.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
            <!-- <el-form-item label="项目id" prop="projectNo">
            <el-input v-model="form.projectNo" placeholder="请输入项目id" />
          </el-form-item> -->

          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitProfitForm">确 定</el-button>
              <el-button @click="cancelProfit">取 消</el-button>
            </div>
          </template>

        </el-dialog>
        <!-- 查看 -->
        <el-dialog v-model="openView" fullscreen="" append-to-body>
          <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="项目信息" name="first">
              <projectView :key="'projectView' + form.projectNo" :datas="form" :isView="isView" :column="3"
                :sizes="'large'" :personList="personList" :attachmentList="attachmentList" :payList="payList"
                :implementList="implementList" :accountingList="accountingList"></projectView>

            </el-tab-pane>
            <el-tab-pane label="正式清单" name="second">
              <mainList v-if="activeName == 'second'" :datas="form"></mainList>
            </el-tab-pane>
            <el-tab-pane label="管家婆出库单" name="third">
              <saleList v-if="activeName == 'third'" :datas="form"></saleList>
            </el-tab-pane>
            <el-tab-pane label="费用汇总" name="four">
              <feeList v-if="activeName == 'four'" :datas="form"></feeList>
            </el-tab-pane>
            <el-tab-pane label="清单对比" name="five">
              <compareMainAndSale v-if="activeName == 'five'" :datas="form"></compareMainAndSale>
            </el-tab-pane>
          </el-tabs>

          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="cancel">关 闭</el-button>
            </div>
          </template>
        </el-dialog>


        <el-dialog title="" fullscreen v-model="openAllocation" width="800px" append-to-body>
          <confirmAllocation ref="allocationRef"></confirmAllocation>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="cancalAllocation">关 闭</el-button>
            </div>
          </template>
        </el-dialog>

      </el-tab-pane>

      <el-tab-pane label="人员统计" name="second">
        <el-table v-loading="loading" :data="moneyRank" border>
          <el-table-column label="姓名" show-overflow-tooltip align="center" prop="personName" />
          <el-table-column label="参与项目数" align="center" show-overflow-tooltip prop="projectCount" />
          <el-table-column label="个人绩效总金额" align="center" show-overflow-tooltip prop="personMoney" />
          <el-table-column label="个人绩效已发放" align="center" show-overflow-tooltip prop="already" />
          <el-table-column label="个人绩效未发放" align="center" prop="wait" show-overflow-tooltip />
          <el-table-column label="部门绩效总金额" align="center" show-overflow-tooltip prop="deptMoney" />
          <el-table-column label="部门绩效已发放" align="center" show-overflow-tooltip prop="deptAlready" />
          <el-table-column label="部门绩效未发放" align="center" show-overflow-tooltip prop="deptWait" />
          <!-- 固定操作列 -->
          <!-- <el-table-column label="操作" fixed="right" width="220" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
              <el-button link type="primary" icon="Edit" @click="openAllocationDialog(scope.row)">绩效发放确认</el-button>
            </template>
          </el-table-column> -->
        </el-table>
        <pagination v-show="rankTotal > 0" :total="rankTotal" v-model:page="rankParams.pageNum"
          v-model:limit="rankParams.pageSize" @pagination="getRanks()" />
      </el-tab-pane>

    </el-tabs>
  </div>

</template>

<script setup name="confirm">
import {
  allocationList,
  getProject, checkMoney,
  listParticipan, getPermission, getMoneyRankPage,
  getStatus, saveUserTableConfig, getUserTableConfig, getAllDetail
} from "@/api/project/project";
import { listAttachment, getAttachment, delAttachment, addAttachment, updateAttachment } from "@/api/project/project";
import { listPay, listImplement, getTotalCost, getPay, delPay, addPay, updatePay, listPhase, getPhase, delPhase, addPhase, updatePhase, listAccounting, getAccounting, delAccounting, addAccounting, updateAccounting } from "@/api/project/project";
import {
  Plus
} from '@element-plus/icons-vue'
import { getInfo } from "@/api/login";
import { listAllUser, getUser, getPosts } from "@/api/system/user";
import { getCheck, getNextPermission, listDictionary, getDictionary, delDictionary, addDictionary, updateDictionary, listAllDictionary } from "@/api/project/dictionary";
import { listFee, delFee, addFee, updateFee, totalFee } from "@/api/project/fee";
const haveNext = ref(false)
const allocationRef = ref()
const openAllocation = ref(false)
import confirmAllocation from "./confirm.vue";
const addPersonPer = ref(false)
const addFilePer = ref(false)
const addPayPer = ref(false)
const addImplementPer = ref(false)
const addWarrantyPer = ref(false)
const addAccountingPer = ref(false)
const loadingQuery = ref(false)
const cw = ref(false)
const allPer = ref(false)

const { proxy } = getCurrentInstance();
const { project_type } = proxy.useDict("project_type");
const { phase_type } = proxy.useDict("phase_type");
const { file_type } = proxy.useDict('file_type');
const { profit_type } = proxy.useDict('profit_type');
const { company_type } = proxy.useDict("company_type");
const { rate_type } = proxy.useDict('rate_type');
const attachmentList = ref([]);
const payList = ref([]);
const posts = ref([])
const userList = ref([])
const projectList = ref([]);
const personList = ref([]);
const companyList = ref([]);
const financeList = ref([]);
const implementList = ref([]);
const accountingList = ref([]);
const open = ref(false);
const openView = ref(false);
const isView = ref(false);
const openOper = ref(false);
const openPhase = ref(false);
const openFile = ref(false);
const openProfit = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAcceptTime = ref([]);
const fileAccept = ref(["doc", "docx", "cad", "dwg", "xls", "ppt", "txt", "pdf", "xlsx", 'png', 'jpg', 'jpeg'],);
const projectNo = ref("")
const contractAmount = ref(0)
const settlementAmount = ref(0)
const materialCost = ref(-1)
const totalMoney = ref(0)
const already = ref(0)
const wait = ref(0)
const bxFee = ref(0)
const finance = ref(false);//当期人员是否是财务
const manger = ref(false);//当前人员是否项目经理
const isAdmin = ref(false);//是否是超级管理员
const havePay = ref(false);//是否有添加付款信息的权限
const status = ref("0");
const currenrPhaseId = ref()
const phasetList = ref([]);
const formDisabled = ref(true);
let currentPhase = reactive({
  phaseCode: '',
});
import { ElLoading } from 'element-plus'
import projectView from "../projectView.vue";
import { ref } from "vue";
import { pa } from "element-plus/es/locale/index.mjs";
import { getToken } from "@/utils/auth";
const data = reactive({
  currentProject: {},
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
  },
  currentConfig: {

  },
  personForm: {
  },
  fileForm: {

  },
  profitForm: {

  },

  profitForm: {

  },

  rankParams: {
    pageNum: 1,
    pageSize: 10,
  },

  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: 2,// 查询核算已完成的  应该查询质保已完成的?
    phaseId: 5,
    finish: 1,//未全部发放的
    projectName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerName: null,
    housekeeperName: null,
    phaseCode: null,
    minProjectAmount: null,
    maxProjectAmount: null
  },
  rules: {
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    approvalDate: [{ required: true, message: "立项日期不能为空", trigger: "blur" }],
    projectType: [{ required: true, message: "项目类型 不能为空", trigger: "blur" }],
  },

  profitRules: {
    type: [{ required: true, message: "请选择类型", trigger: "blur" }],
    projectAmount: [{ required: true, message: "结算总金额不能为空", trigger: "blur" }],
    rate: [{ required: true, message: "未找到税率信息，请联系管理员配置", trigger: "blur" }],

  }


});

const rankTotal = ref(0)

//绩效分配
async function openAllocationDialog(row) {

  //先检查  对应的款都有没有收到

  const res = await checkMoney(row.projectNo).then((response) => {

  });


  reset();
  const _projectNo = row.projectNo || ids.value;
  projectNo.value = row.projectNo //存放项目id
  getProject(_projectNo).then((response) => {
    form.value = response.data;
    openAllocation.value = true

    // 使用 nextTick 确保组件已经渲染
    nextTick(() => {
      if (allocationRef.value) {
        allocationRef.value.initData(form.value, "2", 'accountingComplete', true);
      } else {
        console.error("allocationRef is not available yet!");
      }
    });
  });

}



function cancalAllocation() {
  openAllocation.value = false
  getList()
}




import mainList from "../mainList.vue";
import saleList from "../saleList.vue";
import feeList from "../fee.vue"
import compareMainAndSale from "../compareMainAndSale.vue"
const activeName = ref('first')
function handleClick(item, event) {
  // activeName
  console.log("tabs页面跳转", item.paneName, event)
  activeName.value = item.paneName
}



function setTypeName(id) {
  //对应的名称
  const filteredObjects = profit_type.value.find(item => item.value == id);
  profitForm.value.typeName = filteredObjects.label
  const result = rate_type.value.find(item => item.label == profitForm.value.typeName);
  console.log("profitForm.value.typeName", profitForm.value.typeName);

  console.log("resultresult", filteredObjects.label, result);
  if (!result) {
    proxy.$modal.msgError("未找到此类型的税率信息，请联系管理员配置");
    return
  }
  profitForm.value.rate = result.value


}

function handleBlur(type) {
  if (type == 1) {
    const percentage = parseFloat(profitForm.value.percentage);
    console.log(`付款百分比为: ${percentage}%`);
    // 计算金额并保留两位小数
    profitForm.value.amount = parseFloat((percentage / 100 * profitForm.value.totalAmount).toFixed(2));
    console.log(`计算后的金额为: ${profitForm.amount}`);
  } else {
    const percentage = parseFloat(profitForm.value.percentage);

    console.log(`付款百分比为: ${percentage}%`);
    // 计算金额并保留两位小数
    profitForm.value.receivedPercentage = parseFloat((profitForm.value.receivedAmount / profitForm.value.totalAmount * 100).toFixed(2));
    console.log(`百分比: ${profitForm.value.receivedPercentaget}`);
  }

}



/** 修改付款信息按钮操作 */
function handleUpdateProfit(row) {
  resetProfit();
  const _Id = row.id || ids.value
  getAccounting(_Id).then(response => {
    profitForm.value = response.data;
    openProfit.value = true;
  });
}

// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}


/** 提交按钮 */
function submitProfitForm() {
  proxy.$refs["accountingRef"].validate(valid => {
    if (valid) {
      profitForm.value.projectNo = projectNo.value
      profitForm.value.phaseId = 5
      if (profitForm.value.id != null) {
        updateAccounting(profitForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openProfit.value = false;
          getListParticipan(projectNo.value)
        });
      } else {
        addAccounting(profitForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openProfit.value = false;
          getListParticipan(projectNo.value)
        });
      }
    }
  });
}

/** 删除付款信息按钮操作 */
function handleDeleteProfit(row) {
  const _Id = row.id
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delAccounting(_Id);
  }).then(() => {
    getListParticipan(projectNo.value)
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}




//添加付款信息 销售负责人添加付款信息？
function addProfit() {
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '成本计算中...' });
  // 定义定时任务
  let intervalId = null;

  intervalId = setInterval(() => {
    // 检查 materialCost 是否不等于 -1
    if (materialCost.value != -1) {
      // 关闭加载状态
      loadingInstance.close();
      // 清除定时任务
      clearInterval(intervalId);
      loadingInstance.close()
      console.log('加载状态已关闭');

      // profitForm.value.projectAmount = contractAmount.value//合同签订金额自动带出 取结算金额？
      profitForm.value.projectAmount = settlementAmount.value ?? contractAmount.value;
      profitForm.value.materialCost = materialCost.value
      profitForm.value.costOne = bxFee.value;
      // personList.value = []
      openProfit.value = true
    }
  }, 500); // 每隔 500ms 检查一次

}


const { queryParams, rankParams, form, personForm, payRules, profitRules, fileForm, profitForm, currentConfig } = toRefs(data);


function getCurrUser(id) {
  getPosts(id).then(response => {
    console.log("66666666", response);
  });
}


//判断是否是销售负责人 项目经理 销售 财务 商务

async function isSale() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [2, 5, 6, 7]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  havePay.value = await hasPermisson(params)
  console.log("添加付款信息", havePay.value);

}

//是否是财务
async function isFinance() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [2, 6]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  finance.value = await hasPermisson(params)

  console.log("添加财务信息", finance.value);
  isManger()
}



//是否是项目经理 销售负责人 管理员
async function isManger() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [2, 5]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  manger.value = await hasPermisson(params)
  console.log("是否是项目经理或销售负责人ger.value", manger.value);
}

async function hasPermisson(params) {
  const res = await getPermission(params).then((response) => {
    console.log("权限信息", response.data);
    return response.data
  });
  return res
}


// function getPhaseStatus(){
//   getStatus
// }

function initData() {
  getUser().then(response => {
    posts.value = response.posts;
    console.log("岗位信息", response);
  });
  listAllUser().then(res => {
    console.log("userlist", res);
    userList.value = res
  });

  getInfo().then((res) => {
    console.log("当前用户", res);
    getCurrUser(res.user.userId)
  })
    .catch((error) => {
      console.log("error", error);
    });
}

const moneyRank = ref([])
/** 查询绩效基本信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeAcceptTime && "" != daterangeAcceptTime) {
    // queryParams.value.params["beginAcceptTime"] = daterangeAcceptTime.value[0];
    // queryParams.value.params["endAcceptTime"] = daterangeAcceptTime.value[1];
    queryParams.value.beginAcceptTime = daterangeAcceptTime.value[0];
    queryParams.value.endAcceptTime = daterangeAcceptTime.value[1];
  }
  allocationList(queryParams.value).then((response) => {
    console.log("项目信息", response);
    projectList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
    console.log('projectList', projectList);

  });

  getAllDetail(null).then((response) => {
    console.log("rrrrrrr", response);
    already.value = response.data.already
    totalMoney.value = response.data.totalMoney
    wait.value = response.data.wait

  });

  getMoneyRankPage(rankTotal.value).then((response) => {
    console.log("rankkkkkkkkk", response);
    moneyRank.value = response.data.rows
    rankTotal.value = response.data.total;
  });

}

function getRanks() {
  getMoneyRankPage(rankParams.value).then((response) => {
    console.log("rankkkkkkkkk", response);
    moneyRank.value = response.data.rows
    rankTotal.value = response.data.total;
  });

}

// 取消按钮
function cancel() {
  open.value = false;
  openView.value = false
  reset();
}

// 取消按钮
function cancelProfit() {
  openProfit.value = false;
  resetProfit();
}


//获取用户详细信息
function getUserInfo() {
  getInfo().then((res) => {
    const user = res.user;
    form.value.createUserName = user.nickName;
    form.value.createUserId = user.userId;
    form.value.createDeptName = user.dept.deptName
    form.value.createDept = user.deptId
    console.log("user", form);
  })
    .catch((error) => {
      console.log("error", error);
    });
}
// 表单重置
function reset() {
  form.value = {
    projectNo: null,
    projectName: null,
    createDeptName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerAddress: null,
    customerName: null,
    housekeeperProject: null,
    phaseCode: null,
    remark: null,
    minProjectAmount: null,
    maxProjectAmount: null
  };
  proxy.resetForm("projectRef");
}

function getSummary(param) {
  const { columns, data } = param;

  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }

    const key = column.property;
    const validKeys = [
      'projectAmount',
      'taxAmount',
      'materialCost',
      'costOne',
      'costTwo',
      'costThree',
      'fundCost',
      'laborCost',
      'profit',
      'costFees',
      'differenceFees',
      'beforeProfit',
      'retentionMoney',
      'afterProfit',
      'projectCommission'
    ];

    if (!validKeys.includes(key)) {
      sums[index] = '';
      return;
    }

    const sum = data.reduce((acc, item) => {
      return acc + (Number(item[key]) || 0);
    }, 0);

    sums[index] = sum.toFixed(2);
  });

  return sums;
}

// 表单重置
function resetProfit() {
  profitForm.value = {
    // projectNo: null,
    // projectName: null,
    // createDeptName: null,
    // projectAmount: null,
    // projectType: null,
    // projectUnit: null,
    // acceptTime: null,
    // customerAddress: null,
    // customerName: null,
    // housekeeperProject: null,
    // phaseCode: null,
    // remark: null,
    // minProjectAmount: null,
    // maxProjectAmount: null
  };
  proxy.resetForm("accountingRef");

}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("project/attachment/importTemplate", {
  }, `user_template_${new Date().getTime()}.xlsx`);
};

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


/** 重置按钮操作 */
function resetQuery() {
  daterangeAcceptTime.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.minProjectAmount = null
  queryParams.value.maxProjectAmount = null
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.projectNo);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 新增按钮操作 */
function handleAdd() {
  formDisabled.value = false
  reset();
  personList.value = []
  open.value = true;
  title.value = "添加项目基本信息";
  form.value.startDate = getCurrentDateTime()
  form.value.approvalDate = getCurrentDate()
  getUserInfo()
}

/** 添加立项前期信息 */
function handleUpdate(row) {
  activeName.value = "first"
  reset();
  isView.value = false
  const _projectNo = row.projectNo || ids.value;
  projectNo.value = row.projectNo //存放项目id
  contractAmount.value = row.contractAmount
  settlementAmount.value = row.settlementAmount
  getProject(_projectNo).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改项目基本信息";
  });
  getListParticipan(row.projectNo)
  getNextPer(row.projectNo);
  getProjectFee()
}


function getListParticipan(projectNo) {
  console.log("projectNoprojectNo", projectNo);

  let params = {
    projectNo: projectNo
  }
  listParticipan(params).then((response) => {
    console.log("参与人员", response);
    personList.value = response.data
  });

  listAttachment(params).then((response) => {
    attachmentList.value = response.data;
  });


  listPay(params).then((response) => {
    payList.value = response.data;
  });

  listAccounting(params).then((response) => {
    accountingList.value = response.data;
  });

  listImplement(params).then((response) => {
    implementList.value = response.data;
  });

  //需关联管家婆项目
  getTotalCost(params).then((response) => {
    // accountingList.value = response.data;
    materialCost.value = response.data.totalCost
    console.log("获取总成本", response);
  });



  isFinance()
  isSale()


  getCurrPhase(projectNo)

}


/** 阶段管理操作 */
async function handleView(row) {
  activeName.value = "first"
  formDisabled.value = true
  isView.value = true
  reset();
  getListParticipan(row.projectNo)
  const _projectNo = row.projectNo || ids.value;
  await getProject(_projectNo).then((response) => {
    form.value = response.data;
    openView.value = true;
  });


}


async function nextPhase() {
  //新版点击下一步 1.下一步按钮只开给需要审核的人 隐藏与显示 获取当前配置的环节规则 请求接口校验

  let params = {
    projectNo: projectNo.value,
    id: 5//项目核算
  }
  //校验该环节的所有配置
  const result = await getCheck(params).then(response => {//立项阶段 id写死
    console.log("项目实施校验", response);
    return response
  });
  if (result.data.permission == false) {
    proxy.$modal.msgError(result.data.message);
    return
  }
  //校验通过 更新当前阶段信息

  let updateParams = {
    id: currenrPhaseId.value,
  }
  const updateResult = await updatePhase(updateParams).then((response) => {
    console.log("更新阶段", response);
    return response
  });

  if (updateResult.data.status == 2) {//如果该环节已完成 插入下一个环节
    let addParams = {
      projectNo: projectNo.value,
      phaseId: 6,//项目归档
    }
    addPhase(addParams).then((response) => {

    })
  }

  proxy.$modal.msgSuccess("提交成功");
  status.value = 2
  open.value = false
}


function getCurrPhase(projectNo) {
  let currPhase = {
    projectNo: projectNo,
    phaseId: 5//项目核算 
  }
  getStatus(currPhase).then((response) => {
    console.log("当前阶段信息", response);
    if (response.data == null) {//没有查询到阶段信息  可以点击下一步 插入阶段信息
      //  currenrPhaseId.value = response.data.id
    } else {
      status.value = response.data.status
      currenrPhaseId.value = response.data.id
    }
  });
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/project/export",
    {
      ...queryParams.value,
    },
    `project_${new Date().getTime()}.xlsx`
  );
}

function getCurrentDateTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  // form.startDate =  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};


function getCurrentDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  // form.startDate =  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day}`;
};




function getCurrPhaseConfig() {
  getDictionary(4).then(response => {//项目验收 id写死 
    currentConfig.value = response.data;
  });
}

function getNextPer(projectNo) {
  let params = {
    projectNo: projectNo,
    id: 5//项目核算
  }
  getNextPermission(params).then(response => {//立项阶段 id写死
    console.log("项目前期 下一步权限", response);
    haveNext.value = response.data.permission

    addPersonPer.value = response.data.addPerson
    addFilePer.value = response.data.addFile
    addPayPer.value = response.data.addPay
    addImplementPer.value = response.data.addImplement
    addWarrantyPer.value = response.data.addWarranty
    addAccountingPer.value = response.data.addAccounting
    cw.value = response.data.cw
    allPer.value = response.data.admin

  });
}

function getProjectFee() {
  let param = {
    projectNo: projectNo.value
  }
  totalFee(param).then(response => {
    bxFee.value = response.data;
    console.log("总报销费用", bxFee.value);
  });
}

getCurrPhaseConfig()

getList();
initData()



loadUserColumnConfig()


// 所有可用列配置（可从接口获取）
const allColumns = [
  { label: "项目名称", prop: "projectName", visible: true },
  { label: "发起人", prop: "createUserName", visible: true },
  { label: "合同金额", prop: "contractAmount", visible: true },
  { label: "结算金额", prop: "settlementAmount", visible: true },
  { label: "项目阶段", prop: "phaseName", visible: true },
  { label: "立项日期", prop: "approvalDate", visible: true },
  { label: "上次更新时间", prop: "updateTime", visible: true },
  { label: "预计验收日期", prop: "acceptTime", visible: true },
  { label: "客户名称", prop: "customerName", visible: true },
  { label: "管家婆项目", prop: "housekeeperName", visible: true },
  { label: "项目类型", prop: "projectTypeName", visible: true },
  { label: "阶段确认人", prop: "joinPeople", visible: true },
  { label: "当前操作人", prop: "currentPeople", visible: true },
]

// 用户当前选择的列 props（由 el-checkbox-group 控制）
const selectedProps = ref([])

// 当前可见列列表（根据 selectedProps 排序后的结果）
const visibleColumns = computed(() => {
  return selectedProps.value
    .map(prop => allColumns.find(col => col.prop === prop))
    .filter(Boolean)
})



// 当前可见列（根据用户选择动态变化）
const selectedColumns = ref([...allColumns])


const saveColumnConfig = async () => {

  console.log('保存配置', selectedProps.value);


  // 调用保存到后端的接口
  await saveUserTableConfig({ configs: selectedProps.value, type: "accounting" })
  proxy.$modal.msgSuccess("保存配置成功");

}

const getWidth = (prop) => {
  switch (prop) {
    case 'projectName':
    case 'approvalDate':
    case 'updateTime':
    case 'acceptTime':
      return 200;
    case 'housekeeperName':
      return 300;
    default:
      return undefined;
  }
}

async function loadUserColumnConfig() {
  const res = await getUserTableConfig({ type: "accounting" })

  let defaultOrder = allColumns
    .filter(col => col.visible !== false) // 可以根据 visible 控制是否默认显示
    .map(col => col.prop)

  if (res.data && Array.isArray(res.data)) {
    // 使用用户保存的顺序（只保留合法的 prop）
    selectedProps.value = res.data.filter(prop =>
      allColumns.some(col => col.prop === prop)
    )
  } else {
    // 否则使用默认顺序
    selectedProps.value = defaultOrder
  }
}

import useUserStore from '@/store/modules/user'

const userStore = useUserStore()


</script>


<style scoped>
:global(h2#card-usage ~ .example .example-showcase) {
  background-color: var(--el-fill-color) !important;
}


.el-statistic {
  --el-statistic-content-font-size: 28px;
}

/* .statistic-card {
    height: 100%;
    padding: 10px;
    border-radius: 4px;
    background-color: var(--el-bg-color-overlay);
} */

.statistic-card {
  height: 100%;
  padding-bottom: 20px;
  padding-left: 5vw;
  border-radius: 4px;
  background-color: var(--el-bg-color-overlay);
}

.statistic-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  font-size: 12px;
  color: var(--el-text-color-regular);
  margin-top: 16px;
}

.statistic-footer .footer-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistic-footer .footer-item span:last-child {
  display: inline-flex;
  align-items: center;
  margin-left: 4px;
}

.green {
  color: var(--el-color-success);
}

.red {
  color: var(--el-color-error);
}

/* 

:deep(.el-table .warning-row) {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
} */

/* 悬停效果 */
/* :deep(.el-table .warning-row:hover td) {
    --el-table-tr-bg-color: var(--el-color-warning-light-8);
    background-color: var(--el-table-tr-bg-color);
} */

/* 如果需要更醒目的边框样式 */
/* :deep(.el-table .warning-row td) {
    border-bottom: 1px solid var(--el-color-warning-light-5);
    border-top: 1px solid var(--el-color-warning-light-5);
}

:deep(.el-table .warning-row td:first-child) {
    border-left: 1px solid var(--el-color-warning-light-5);
}

:deep(.el-table .warning-row td:last-child) {
    border-right: 1px solid var(--el-color-warning-light-5);
} */



/* 如果需要更醒目的边框样式 */
/* :deep(.el-table .success-row td) {
    border-bottom: 1px solid var(--el-color-warning-light-5);
    border-top: 1px solid var(--el-color-warning-light-5);
}

:deep(.el-table .success-row td:first-child) {
    border-left: 1px solid var(--el-color-warning-light-5);
}

:deep(.el-table .success-rowtd:last-child) {
    border-right: 1px solid var(--el-color-warning-light-5);
} */
.mobile-span-24 {
  width: 100%;
  max-width: 100%;
  flex: 0 0 100%;
}
</style>